#!/bin/sh
# nosignal-reboot-check — tell the user to reboot when a kernel update has landed.
#
# Signal: a kernel package upgrade replaces /usr/lib/modules/<running>. If the
# running kernel's modules directory is gone, the new kernel is on disk but not
# running — the live session can't load fresh modules and the new UKI isn't
# booted yet → a reboot is required. Writes a stamp so a login check can re-warn
# until the reboot actually happens; clears it once running == on-disk again.
#
# Safe to run anytime (read-only except the stamp). Used by nosignal-update at
# the end of an update, and may be called at login.
set -u

STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/nosignal"
STAMP="$STATE_DIR/reboot-required"
running=$(uname -r)

if [ -d "/usr/lib/modules/$running" ]; then
  # Running kernel still installed → nothing pending; clear any stale stamp.
  [ -f "$STAMP" ] && rm -f "$STAMP"
  exit 0
fi

# Running kernel's modules were removed by an update → reboot needed.
mkdir -p "$STATE_DIR"; : > "$STAMP"
newest=$(ls -1 /usr/lib/modules/ 2>/dev/null | grep -vx "$running" | sort -V | tail -1)
msg="Kernel updated — reboot to load it"
[ -n "$newest" ] && msg="$msg ($running → $newest)"
msg="$msg."

# Terminal banner (visible when run from nosignal-update).
printf '\n\033[1;33m::  %s\033[0m\n' "$msg"
printf '\033[1;33m::  At the Limine menu, boot the UKI entry (\"Linux\"/NoSignal UKI).\033[0m\n\n'

# Desktop notification (best effort; only meaningful inside a user session).
if command -v notify-send >/dev/null 2>&1; then
  notify-send -u critical -i system-reboot "NoSignal: reboot required" \
    "$msg
Boot the UKI entry at the Limine menu." 2>/dev/null || true
fi
exit 0
